from flask import Blueprint, request, jsonify, render_template
from app.agent.agent import init
from app.agent.quant_params import QuantParams
from app.agent.state import QuantState
import json

agent_bp = Blueprint('agent', __name__, template_folder='../templates')


@agent_bp.route('/control', methods=['GET'])
def control_panel():
    return render_template('agent_control.html')


# 初始化图应用
app = init()


@agent_bp.route('/execute_workflow', methods=['POST'])
def execute_workflow():
    request_data = request.json
    print(request_data)
    asset_class = request_data.get("asset_class", "国债")

    if asset_class == "外汇":
        params = QuantParams(
            asset_class=asset_class,
            currency_pair=request_data.get("currency_pair", "EUR/USD"),
            leverage_ratio=request_data.get("leverage_ratio", 50),
            time_frame=request_data.get("time_frame", "1小时"),
            max_drawdown=request_data.get("max_drawdown", 0.15),
            data_sources=json.loads(request_data.get("data_sources", '["L2订单簿", "宏观经济指标"]'))
        )
    elif asset_class == "贵金属":
        params = QuantParams(
            asset_class=asset_class,
            metal_type=request_data.get("metal_type", "黄金"),
            market=request_data.get("market", "期货主力合约"),
            time_frame=request_data.get("time_frame", "日线"),
            volatility_profile=request_data.get("volatility_profile", "常态波动"),
            carry_cost=float(request_data.get("carry_cost", 0.0002)),
            max_leverage=float(request_data.get("max_leverage", 5.0)),
            data_sources=json.loads(request_data.get("metal_data_sources", '["价格", "持仓量", "美元指数"]')),
            max_drawdown=request_data.get("max_drawdown", 0.1)
        )
    else:
        params = QuantParams(
            asset_class=asset_class,
            bond_duration=request_data.get("bond_duration", "中端(3-7Y)"),
            time_frame=request_data.get("time_frame", "日线"),
            max_drawdown=request_data.get("max_drawdown", 0.1),
            data_sources=json.loads(request_data.get("data_sources", '["宏观经济指标", "央行政策文本"]')),
            credit_rating=request_data.get("credit_rating", "AAA")
        )

    state = QuantState(params=params, features={}, raw_data=None, processed_data=None,
                       candidate_factors=[], backtest_results={}, selected_factors=[])
    results = {}
    try:
        results = app.invoke(state)
        results["candidate_factors"] = state["candidate_factors"]
        results["backtest_results"] = state["backtest_results"]
        results["selected_factors"] = state["selected_factors"]
        return jsonify({
            'success': True,
            'results': results
        })

    except Exception as e:
        print(str(e))
        msg = jsonify({
            'success': False,
            'error': str(e),
            'results': results
        })
        return msg, 500
